package com.dayaokeji.rhythmschoolstudent.client.message;


import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.beetle.bauhinia.db.ICustomerMessage;
import com.dayaokeji.imkitwrapper.fragment.MessageListFragment;
import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.ApiConstantKt;
import com.dayaokeji.rhythmschoolstudent.client.common.base.common.BaseFragment;
import com.dayaokeji.rhythmschoolstudent.client.main.MainFragment;
import com.dayaokeji.rhythmschoolstudent.client.mine.bulletin.BulletinActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.group.GroupActivity;
import com.dayaokeji.rhythmschoolstudent.event.GroupEvent;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.GroupApi;
import com.dayaokeji.server_api.api.UserApi;
import com.dayaokeji.server_api.domain.Group;
import com.dayaokeji.server_api.domain.UserInfo;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import retrofit2.Call;

/**
 *  conversations list
 *  消息界面
 */
public class ConversationsFragment extends BaseFragment implements MainFragment{

    private static final String MESSAGE_LIST_TAG = "message_list_tag";
    private static final String EXTRA_SHOW_ACTION_BAR = "show_action_bar";

    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.appbar)
    AppBarLayout appBarLayout;

    private MessageListFragment messageListFragment;

    private UserApi userApi = ApiUtils.getApi(UserApi.class);
    private final GroupApi groupApi = ApiUtils.getApi(GroupApi.class);
    private Call<ServerResponse<UserInfo>> userDetailCall;
    private Call<ServerResponse<Group>> selectGroupByIdCall;

    private boolean showActionBar = true;

    public static ConversationsFragment newInstance(boolean showActionBar) {

        Bundle args = new Bundle();
        args.putBoolean(EXTRA_SHOW_ACTION_BAR, showActionBar);
        ConversationsFragment fragment = new ConversationsFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    protected View onCreate(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (getArguments() != null) {
            showActionBar = getArguments().getBoolean(EXTRA_SHOW_ACTION_BAR,true);
        }
        return inflater.inflate(R.layout.fragment_conversations, container, false);
    }

    @Override
    public Toolbar getToolbar() {
        return toolbar;
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        EventBus.getDefault().register(this);
        setHasOptionsMenu(true);
        appBarLayout.setVisibility(showActionBar ? View.VISIBLE : View.GONE);
        messageListFragment = (MessageListFragment) getChildFragmentManager().findFragmentByTag(MESSAGE_LIST_TAG);
        if (messageListFragment == null) {
            messageListFragment = MessageListFragment.newInstance(UserUtils.getCurrentUid());
        }
        //加入消息列表界面
        getChildFragmentManager().beginTransaction().replace(R.id.fl_content, messageListFragment,MESSAGE_LIST_TAG).commit();

        messageListFragment.setConversationOnItemClickListener(new MessageListFragment.ConversationOnItemClickListener() {
            @Override
            public void onChat(MessageListFragment.User u) {//CONVERSATION_PEER
                String name = TextUtils.isEmpty(u.name)?u.identifier : u.name;
                ChatActivity.navigation(getActivity(), u.uid, name);
            }

            @Override
            public void onGroup(MessageListFragment.Group group) {//CONVERSATION_GROUP
                String name = TextUtils.isEmpty(group.name) ? group.identifier : group.name;
                GroupChatActivity.navigation(getActivity(), group.gid,name);
            }

            @Override
            public void onCustomer(ICustomerMessage iCustomerMessage) {//CONVERSATION_CUSTOMER_SERVICE
                CustomerMessageActivity.navigation(getActivity(), UserUtils.getCurrentUid(), iCustomerMessage.storeID, iCustomerMessage.sellerID);
            }

            @Override
            public void onGroups() {//点击群组
                GroupActivity.navigation(getActivity());
            }

            @Override
            public void onNotice() {//点击了通知
                BulletinActivity.navigation(getActivity());
            }
        });

        messageListFragment.setGroupInfoCallback(new MessageListFragment.GroupInfoCallback() {

            @Override
            public void callback(final long gid, final MessageListFragment.GetGroupCallback cb) {

                selectGroupByIdCall = groupApi.selectGroupById(gid);
                selectGroupByIdCall.enqueue(new ServerCallback<Group>() {
                    @SuppressLint("DefaultLocale")
                    @Override
                    public void onResponse(boolean success, ServerResponse<Group> response) {
                        if (success) {
                            Group group = response.getBody();
                            if (group != null) {
                                MessageListFragment.Group g = new MessageListFragment.Group();
                                g.gid = gid;
                                g.name = group.getName();
                                g.avatarURL = "";
                                g.identifier = group.getName();
                                cb.onGroup(g);
                            }else{
                                MessageListFragment.Group g = new MessageListFragment.Group();
                                g.gid = gid;
                                g.name = String.format("%d", gid);
                                g.avatarURL = "";
                                g.identifier = String.format("%d", gid);
                                if (getActivity() != null && !getActivity().isFinishing()) {
                                    cb.onGroup(g);
                                }
                            }
                        }
                    }
                });
            }
        });

        messageListFragment.setUserInfoCallback(new MessageListFragment.UserInfoCallback() {
            @SuppressLint("DefaultLocale")
            @Override
            public void callback(final long uid, final MessageListFragment.GetUserCallback cb) {
                if (UserUtils.getCurrentUid() == uid) {
                    MessageListFragment.User user = new MessageListFragment.User();
                    user.uid = uid;
                    UserInfo userInfo = UserUtils.getUserInfo();
                    if (userInfo != null) {
                        user.identifier = userInfo.getName() == null ? "" : userInfo.getName();
                        user.name = userInfo.getName() == null ? "" : userInfo.getName();
                        String pictureId = userInfo.getPictureId();
                        user.avatarURL = ApiConstantKt.getRemoteImageUrl()+ (TextUtils.isEmpty(pictureId) ? "" : pictureId);
                    }
                    if (getActivity() != null && !getActivity().isFinishing()) {
                        cb.onUser(user);
                    }
                }else{
                    if (uid != 0) {
                        userDetailCall = userApi.userDetail(uid);
                        userDetailCall.enqueue(new ServerCallback<UserInfo>() {
                            @SuppressLint("DefaultLocale")
                            @Override
                            public void onResponse(boolean success, ServerResponse<UserInfo> response) {
                                if (success) {
                                    MessageListFragment.User user = new MessageListFragment.User();
                                    user.uid = uid;
                                    Logger.d("im user name === "+user.name);
                                    if (response.getBody() != null) {
                                        UserInfo userInfo = response.getBody();
                                        user.identifier = userInfo.getName();
                                        user.name = userInfo.getName();
                                        user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                                    }else{
                                        user.name = String.format("%d", uid);
                                        user.avatarURL = "";
                                    }
                                    if (getActivity() != null && !getActivity().isFinishing()) {
                                        cb.onUser(user);
                                    }
                                }
                            }
                        });
                    }else{
                        MessageListFragment.User user = new MessageListFragment.User();
                        user.uid = uid;
                        user.identifier = String.format("%d", uid);
                        UserInfo userInfo = UserUtils.getUserInfo();
                        if (userInfo != null) {
                            user.name = userInfo.getName() == null ? "" : userInfo.getName();
                            user.avatarURL = ApiConstantKt.getRemoteImageUrl()+(TextUtils.isEmpty(userInfo.getPictureId()) ? "" : userInfo.getPictureId());
                        }
                        if (getActivity() != null && !getActivity().isFinishing()) {
                            cb.onUser(user);
                        }
                    }
                }

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDelAndExistGroup(GroupEvent groupEvent) {
        if (messageListFragment != null && groupEvent != null) {
            messageListFragment.delAndExistGroup(groupEvent.getId());
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (userDetailCall != null) {
            userDetailCall.cancel();
        }

        if (selectGroupByIdCall != null) {
            selectGroupByIdCall.cancel();
        }

        EventBus.getDefault().unregister(this);
    }
}
